// 必须先点击web 才可以 触发 play 事件
import * as THREE from "three";
import { GUI } from "three/addons/libs/lil-gui.module.min.js";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

let body = document.getElementById("body");
body.onclick = () => {
  let music = document.getElementById("bg_music");
  music.play();
};

// regis start play button
let start_div = document.getElementById("start_div");
start_div.onclick = hidden_start_button;

function hidden_start_button() {
  start_play();
  let start_div = document.getElementById("start_div");
  start_div.remove();
}

function start_play() {
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );

  const ambient = new THREE.AmbientLight(0xffffff, 0.5);
  scene.add(ambient);

  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  const geometry = new THREE.BoxGeometry(4, 4, 4);
  const reflectionCube = new THREE.CubeTextureLoader()
    .setPath("./cube_maps/")
    .load(["1.jpg", "2.jpg", "1.jpg", "2.jpg", "3.jpg", "4.jpg"]);
  //, envMap: reflectionCube
  // const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
  // 带有光线反射的材质
  const material = new THREE.MeshPhongMaterial({ envMap: reflectionCube });

  const cube = new THREE.Mesh(geometry, material);
  scene.add(cube);

  camera.position.z = 5;

  // add controller
  const gui = new GUI();
  gui.add(ambient, "intensity", 0, 1).name("光线亮度");
  gui.add(camera.position, "z", 4, 10).name("相机位置");

  let rotation_speed = {};
  rotation_speed.x = 0.0;
  rotation_speed.y = 0.003;
  rotation_speed.z = 0.0;

  gui.add(rotation_speed, "x", 0.0, 0.1).name("旋转速度x");
  gui.add(rotation_speed, "y", 0.0, 0.1).name("旋转速度y");
  gui.add(rotation_speed, "z", 0.0, 0.1).name("旋转速度z");

  function animate() {
    requestAnimationFrame(animate);

    cube.rotation.x += rotation_speed.x;
    cube.rotation.y += rotation_speed.y;
    cube.rotation.z += rotation_speed.z;

    renderer.render(scene, camera);
  }

  animate();

  // add cama
  let controls = new OrbitControls(camera, renderer.domElement);
  controls.listenToKeyEvents(window); // optional

  //controls.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)

  controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
  controls.dampingFactor = 0.05;

  controls.minDistance = 4;
  controls.maxDistance = 10;

  // controls.screenSpacePanning = false;
  // controls.maxPolarAngle = Math.PI / 2;
}
